package wat.serwerapp.usermgmt.ldap;

import java.util.HashMap;
import java.util.Map;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;

/**
 *
 * @author P.B. & L.G. & K.K.
 */
public class MethodManager {
    private static final String METHOD_SUFIX = ",ou=methods,dc=wat,dc=edu,dc=pl";
    private static final String METHODS = "ou=methods,dc=wat,dc=edu,dc=pl";
    private static final String FILE_ATTRIBUTE_NAME = "destinationIndicator";

    // tego nie buforujemy - jest to robione gdzie indziej
    // private static Map<String,String> buffer = new HashMap<String,String>();
    public static Map<String, String> getMethods() throws NamingException {

        HashMap<String, String> methods = new HashMap<String, String>();

        DirContext ctx = LdapConnector.getRolesContext();
        NamingEnumeration<NameClassPair> list = ctx.list(METHODS);
        while (list.hasMore()) {
            NameClassPair nc = list.next();
            String cn = nc.getName();

            Attributes att = ctx.getAttributes(cn + METHOD_SUFIX);
            Attribute a = att.get(FILE_ATTRIBUTE_NAME);
            if (a != null) {
                String file = (String) a.get(0);
                System.out.println("METHODS:::put: " + cn.substring(3) + " - " + file);
                methods.put(cn.substring(3), file);
            }
        }
        return methods;
    }

    public static void addMethod(String methodName, String methodPath) throws NamingException {
             DirContext ctx = LdapConnector.getRolesContext();

            Attributes att = new BasicAttributes();
            Attribute a = new BasicAttribute("destinationIndicator");
            a.add(methodPath);
            Attribute c = new BasicAttribute("objectClass");
            c.add("organizationalRole");
            c.add("top");
            att.put(c);
            att.put(a);

            ctx.createSubcontext("cn=" + methodName + METHOD_SUFIX, att);
    }

    public static String methodFromLdapFormat(String role) {
        int beginIndex = 3;
        int endIndex = role.indexOf(METHOD_SUFIX);
        return role.substring(beginIndex, endIndex);
    }

    public static String methodToLdapFormat(String role) {
        return "cn=" + role + METHOD_SUFIX;
    }
}
